<template>
<q-layout view="hHh Lpr fFf">
    <!-- Be sure to play with the Layout demo on scripts -->

    <!-- (Optional) The Header -->
    <q-header reveal :class="isShow?'back-dark shadow-7':'transparent'">
        <q-toolbar class="transparent " style="width: 100%; height: 50px">
            <q-btn @click="handleBack" flat dense round icon="mdi-keyboard-backspace"></q-btn>
            <q-btn flat round size="15px" dense icon="list" @click="leftDrawer = !leftDrawer" />
            <div class="text-subtitle1">{{projectInfo.name}}</div>
            <!-- <q-btn flat  dense icon="mdi-content-save-outline"  />
            <span class="text-caption text-grey-8">自动保存</span> -->

            <q-space></q-space>
            <q-bar dark style="height: 60px" class="transparent row q-pa-none justify-between">

                <q-space />

                <q-btn size="14px" flat dense icon="share" />

                <q-btn size="14px" flat dense @click="handleMinWin" :class="isShow?'':'shadow-7'" icon="mdi-filter-outline" class="items-center">

                </q-btn>
                <q-btn size="14px" flat dense icon="mdi-eye-outline" @click="handleHide">

                </q-btn>
                <q-btn size="14px" flat dense :class="isShow?'':'shadow-7'" icon="menu">
                    <q-menu size="14px" content-class="bg-grey-9 text-white" anchor="bottom right" self="top right" :offset="[0,10]">
                        <q-item dense clickable>
                            <q-item-section dense avatar style="min-width:20px" class="q-pa-sm">
                                <q-icon name="mdi-plus"></q-icon>
                            </q-item-section>
                            <q-item-section>新版本</q-item-section>
                        </q-item>

                        <q-item dense clickable>
                            <q-item-section dense avatar style="min-width:20px" class="q-pa-sm">
                                <q-icon name="mdi-database-export-outline"></q-icon>
                            </q-item-section>
                            <q-item-section>导出数据</q-item-section>
                        </q-item>
                        <q-separator inset color="grey-4"></q-separator>
                        <q-item dense clickable>
                            <q-item-section dense avatar style="min-width:20px" class="q-pa-sm">
                                <q-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                                        <title>printer-outline</title>
                                        <path d="M19 8C20.66 8 22 9.34 22 11V17H18V21H6V17H2V11C2 9.34 3.34 8 5 8H6V3H18V8H19M8 5V8H16V5H8M16 19V15H8V19H16M18 15H20V11C20 10.45 19.55 10 19 10H5C4.45 10 4 10.45 4 11V15H6V13H18V15M19 11.5C19 12.05 18.55 12.5 18 12.5C17.45 12.5 17 12.05 17 11.5C17 10.95 17.45 10.5 18 10.5C18.55 10.5 19 10.95 19 11.5Z" />
                                    </svg></q-icon>
                            </q-item-section>
                            <q-item-section>打印</q-item-section>
                        </q-item>
                    </q-menu>
                </q-btn>
                <!-- <q-btn dense flat icon="close"><q-tooltip>关闭项目</q-tooltip></q-btn> -->
            </q-bar>
            <!-- <q-btn flat round dense icon="menu" class="mobile-only q-mr-sm" /> -->
        </q-toolbar>
    </q-header>

    <!-- (Optional) The Footer -->
    <q-footer v-model="isShow" class="row back-dark items-center shadow-up-7" style="height:40px">
        <q-btn flat round size="15px" dense icon="list" @click="leftDrawer = !leftDrawer" />

    </q-footer>

    <!-- (Optional) A Drawer; you can add one more with side="right" or change this one's side -->
    <q-drawer v-model="hideDrawer" :overlay="true" :width="300" :breakpoint="100" side="right" class="shadow-7" content-class="bg-dark " :behavior="!$platform.inDesktop()?'mobile':'default'">

        <q-scroll-area style="height: calc(100% - 80px); margin-top: 80px" class="q-px-md ">

            <q-card class="back-dark row items-center q-my-sm" v-for="item,index in colList" :key="index">
                <!-- <q-toggle
        v-model="item.fixed"
        checked-icon="mdi-lock-outline"
        true-value="left"
        :false-value="!item.fixed"
        color="green"
        @input="handleFixedCol(item,'left')"
        unchecked-icon="mdi-lock-open-variant-outline"
      /> -->
                <!-- <q-btn flat round size="15px"  dense :icon="item.fixed?'mdi-lock-outline':'mdi-lock-open-variant-outline'" @click="handleFixedCol('left')" /> -->
                <!-- <span class="col-3">{{ item.title}}</span> -->

                <q-toggle class="col-6" v-model="item.visible" checked-icon="mdi-eye-outline" :label="item.title" @input="handleToggleCol(item)" color="teal-4" unchecked-icon="mdi-eye-off-outline" />
                <div class="col-6 q-gutter-x-sm">
                    <q-btn size="10px" flat round :icon="item.fixed=='left' || item.fixed=='right'?'mdi-lock-outline':'mdi-lock-open-variant-outline'" @click="handleFixedCol(item,index,null)"></q-btn>

                    <q-radio size="25px" dark color="primary" v-model="item.fixed" val="left" label="左" @input="handleFixedCol(item,index,'left')" />
                    <q-radio size="25px" dark v-model="item.fixed" val="right" label="右" @input="handleFixedCol(item,index,'right')" />
                </div>

            </q-card>

        </q-scroll-area>
        <q-card flat class="absolute-top transparent q-py-sm q-px-md q-mt-md" style="height: 80px">
            <div class="bg-transparent row justify-between">
                <div class="text-weight-bold text-h6">列控制 <span class="text-caption">（显示和固定）</span>

                </div>
                <q-btn flat round size="15px" dense icon="mdi-unfold-more-vertical" @click="hideDrawer = !hideDrawer" />
                <!-- <q-btn dense color="primary" outline icon="add" label="新建"></q-btn> -->
            </div>
            <q-separator color="grey-7" class="q-my-md"></q-separator>
        </q-card>

    </q-drawer>
    <q-drawer v-model="leftDrawer" :overlay="!$platform.inDesktop()" :width="300" :breakpoint="100" side="left" class="shadow-7" content-class="bg-dark " :behavior="!$platform.inDesktop()?'mobile':'default'">
        <!-- QScrollArea is optional -->
        <q-scroll-area style="height: calc(100% - 80px); margin-top: 80px" class="q-px-md ">

            <q-list class="text-teal-3">

                <q-item class="column q-mt-sm q-pa-none q-mb-sm shadow-7 " clickable v-for="item,index in scriptList" :key="index" :active="curScript==item.script_id" @click.stop="handlescriptSelect(item)" v-ripple active-class="bg-teal-8 text-white">
                    <q-item-section :class="curScript==item.script_id?'':'bg-grey-9'">
                        <q-card class=" q-pa-sm bg-transparent  column item-center">
                            <tips-title lineColor="grey-6" :isPad="false" :title.sync="item.script_name" tipStyle="height:40px" class="text-subtitle1" :isTitleEdit.sync="item.isTitleEdit" @click.native.stop="handleEditTitle(item)"></tips-title>
                            <div class="q-py-sm row items-center  justify-between ">
                                <div>
                                    <div>
                                        <q-icon class="q-mr-sm" name="mdi-clock-time-twelve-outline"></q-icon>{{ item.format_ctime }}
                                    </div>
                                    <!-- <div>
                                  <q-icon class="q-mr-sm" name="mdi-clock-outline"></q-icon>{{item.etime}}
                              </div> -->
                                </div>

                                <div class="row flex-center">
                                    <q-badge v-if="item.task_status==0" class="q-pa-sm" color="cyan-4">待开始</q-badge>
                                    <q-badge v-if="item.task_status==1" class="q-pa-sm" color="cyan-6">已完成</q-badge>
                                </div>
                            </div>

                        </q-card>
                    </q-item-section>

                    <!-- <q-item-section>
                  <q-badge>{{item.ctime}}</q-badge>
              </q-item-section>
              <q-item-section>{{item.taskname}}</q-item-section> -->
                </q-item>

                <q-separator />

            </q-list>

        </q-scroll-area>
        <q-card flat class="absolute-top transparent q-py-sm q-px-md q-mt-md" style="height: 80px">
            <div class="bg-transparent row justify-between">
                <div class="text-weight-bold text-h6">脚本列表
                    <q-btn flat round size="15px" dense icon="mdi-unfold-more-vertical" @click="leftDrawer = !leftDrawer" />
                </div>
                <q-btn dense color="primary" outline icon="add" @click="handleAddScript" label="新建"></q-btn>
            </div>
            <q-separator color="grey-7" class="q-my-md"></q-separator>
        </q-card>

    </q-drawer>

    <q-page-container>

        <!-- This is where pages get injected -->
        <router-view ref="scriptContainer" :user="user" :isShow="isShow" />
    </q-page-container>

</q-layout>
</template>

<script>
import {
    customAlphabet
} from 'nanoid';
import {
    addscript,
    loadscriptList
} from "assets/api/studio/script"
import htmlToJson from "html-to-json"
import {
    loadDoc,

} from "assets/api/studio/doc"
export default {

    data() {
        return {
            hideDrawer: false,
            pid: '',
            leftDrawer: true,
            isFull: false,
            isShow: true,
            projectInfo: {
                name: ''
            },
            scriptList: [],
            curScript: '',
            colList: []

        }
    },
    created() {
        this.pid = this.$route.params.pid;

        this.projectInfo = this.$store.state.projectinfo;
        this.handleLoadscriptList()
        this.user = this.$store.state.user;
        if (this.$route.query.doc_id) {
            this.doc_id = this.$route.query.doc_id;

        }

    },
    mounted() {
        this.$emit('isSingle', true)
        this.i_name = setInterval(() => {
          this.projectInfo = this.$store.state.projectinfo;
            if (this.projectInfo.name) {
                document.title = this.projectInfo.name + '--脚本';
                clearInterval(this.i_name)
            }

        }, 500);

    },
    watch: {
        '$q.fullscreen.isActive'(val) {
            // if (val) {
            //     this.isShow = false;
            // } else {
            //     this.isShow = true;
            // }

            console.log(val ? 'In fullscreen now' : 'Exited fullscreen')
        }
    },
    beforeDestroy() {
        this.$emit('isSingle', false)
        this.$q.loading.hide()
    },
    methods: {
        handleLoadDoc() {
            this.$q.loading.show()
            var vm = this;
            loadDoc({
                doc_id: this.doc_id
            }).then(res => {

                if (res.data.code == 1) {
                    let data = res.data.data[0];

                    let json = htmlToJson.parse(data.content, function () {
                        return this.map('span', function ($item) {
                            return $item.text();
                        })

                    })
                    json.done(res => {

                        let newArr = Array.from(new Set(res))

                        let format_arr = []
                        let script_data = []
                        newArr.forEach((i, index) => {
                            let arr = i.split(/。|；|！/ig)
                            if (arr.length > 0) {
                                arr.forEach(item => {
                                    if (item.length > 0) {
                                        format_arr.push(item)
                                    }

                                })
                            } else {
                                format_arr.push(i)
                            }

                        })
                        format_arr.forEach((i, index) => {

                            script_data.push({
                                scene: 1,
                                shot: index + 1,
                                position: '',
                                narrate: i,
                                desc: '',
                                scale: [],
                                method: [],
                                duration: '2',
                                effect: '否',
                                music: '',
                                sound: '',

                                refer: [],
                                links: [],
                                memberList: [],
                                isShot: '否',
                                status: '待开始',
                                stime: '',
                                etime: '',
                                remark: ''
                            })

                        })

                        var nanoid = customAlphabet('123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 18);
                        let script_id = nanoid()
                        let ctime = new Date().getTime()
                        let format_ctime = this.$moment(ctime, 'x').calendar();

                        let script = {
                            pid: this.pid,
                            script_id,
                            script_name: data.doc_name,
                            isTitleEdit: false,
                            content: script_data,
                            ctime,
                            format_ctime,
                            version: 1
                        }

                        vm.scriptList.push(script);
                        console.log(vm.scriptList);
                        addscript(script).then(res => {
                            if (res.data.code == 1) {
                                this.$message.success('脚本生成成功！')
                            } else {
                                this.$message.error('脚本生成失败！')
                            }
                        })
                        this.$refs.scriptContainer.script = script
                        this.$refs.scriptContainer.loadFromDoc()
                        this.curScript = script_id;
                        // vm.$q.loading.hide()
                    })
                }
            })
        },
        handleAddScript() {
            this.$q.loading.show()
            const nanoid = customAlphabet('123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 18);
            let script_id = nanoid()
            let ctime = new Date().getTime()
            let format_ctime = this.$moment(ctime, 'x').calendar();
            let script = {
                pid: this.pid,
                script_id,
                script_name: '未命名脚本',
                isTitleEdit: false,
                content: '',
                ctime,
                format_ctime,
                version: 1
            }

            this.scriptList.push(script);
            this.$refs.scriptContainer.script = script
            // this.$refs.scriptContainer.loadscriptEngine()
            // this.$refs.scriptContainer.autoSave()
            this.curScript = script_id;
            this.$q.loading.hide()
            addscript(script).then(res => {
                console.log(res);
            })
        },
        handlescriptSelect(item) {
            this.curScript = item.script_id
            this.$refs.scriptContainer.script = item;
            this.$refs.scriptContainer.loadFromDoc()

            this.scriptMsg = ''
        },
        handleEditTitle(item) {
            console.log(item);
            item.isTitleEdit = true
        },
        handleToggleCol(item) {
            this.$refs.scriptContainer.$refs.ShotTabel.hideColumn(item.title).then(res => {

            })
        },
        handleFixedCol(item, index, val) {
            let col = this.$refs.scriptContainer.$refs.ShotTabel.getTableColumn().fullColumn;
            col[index].fixed = val
            this.$refs.scriptContainer.$refs.ShotTabel.refreshColumn()
        },
        handleLoadscriptList() {
            loadscriptList({
                pid: this.pid
            }).then(res => {
                console.log(res);
                if (res.data.code == 1) {
                    let data = res.data.data;
                    console.log(data);
                    data.forEach(i => {
                        i.format_ctime = this.$moment(i.ctime, 'x').calendar();
                        i.isTitleEdit = false
                        i.content = JSON.parse(i.content)
                    })
                    this.scriptList = data
                    if (this.$route.query.doc_id) {
                        this.handleLoadDoc()
                    }
                }
            })
        },
        handleHide() {
            this.hideDrawer = !this.hideDrawer
            let col = this.$refs.scriptContainer.$refs.ShotTabel.getTableColumn().fullColumn;
            console.log(col);
            this.colList = col
        },
        handleBack() {
            this.$router.replace('/studio/' + this.pid)
        },

        handleMinWin() {
            // this.isShow = false;
            this.$q.fullscreen
                .exit()
                .then(() => {
                    // v1.5.0+
                    // success!
                })
                .catch((err) => {
                    // v1.5.0+
                    // oh, no!!!
                });
        },
        handleMaxWin() {
            // this.isShow = false;
            this.$q.fullscreen
                .request()
                .then(() => {
                    console.log(this.$refs);
                })
                .catch((err) => {
                    // v1.5.0+
                    // oh, no!!!
                });
        },
        handleUploadDialog() {
            this.isUploadDialog = true;
        }

    }
}
</script>
